package com.zhu.websocketdemo.websocket;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhu.websocketdemo.pojo.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MessageBroadcaster {
    private static final String CHANNEL = "chat_channel";

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private SimpleChatHandler simpleChatHandler;

    private ObjectMapper objectMapper = new ObjectMapper();
    // 发送消息到频道
    public void broadcast(String message) {
        redisTemplate.convertAndSend(CHANNEL, message);
    }

    // 消息监听容器（需配置）
    @Bean
    public MessageListenerAdapter listenerAdapter() {
        return new MessageListenerAdapter(new MessageListener() {
            @Override
            public void onMessage(Message message, byte[] pattern) {
                String channel = new String(message.getChannel()); // 获取频道名称
                String msg = new String(message.getBody());
                System.out.println("收到来自频道 [" + channel + "] 的消息: " + msg);
                ///如何将此消息广播给前端页面？
                processMessage(msg);
            }
        });
    }


    /**
     * 处理消息
      * @param msg 消息内容
     */
    private void processMessage(String msg){
        if (msg.startsWith("\"") && msg.endsWith("\"")) {
            msg = msg.substring(1, msg.length() - 1);
        }
        msg = msg.replace("\\\"", "\"");
        // 将消息转换为ResponseMessage对象
        if (msg.startsWith("ONLINE_USERS:")) {
            // 处理 ONLINE_USERS 类型的消息
            String users = msg.substring("ONLINE_USERS:".length());
            System.out.println("当前在线用户: " + users);
            // 广播给前端页面
            simpleChatHandler.broadcastMessage(msg);
            simpleChatHandler.sendMessageRank();
        } else {
            // 将其他类型的消息转换为 ResponseMessage 对象
            ResponseMessage responseMessage = null;
            try {
                responseMessage = objectMapper.readValue(msg, ResponseMessage.class);
                System.out.println("解析后的消息对象: " + responseMessage);
            } catch (IOException e) {
                System.err.println("解析消息失败: " + e.getMessage());
                throw new RuntimeException(e);
            }
            if ("GROUP".equals(responseMessage.getType())){
                broadcastMessage(responseMessage);
            }else {
                privateMessage(responseMessage.getToUser().split(","), responseMessage);
            }

        }
    }

    /**
     * 广播消息
     * @param responseMessage
     */
    public void broadcastMessage(ResponseMessage responseMessage){
        try {
            simpleChatHandler.broadcastMessage(objectMapper.writeValueAsString(responseMessage));
            simpleChatHandler.sendMessageRank();
        } catch (JsonProcessingException e) {
            System.err.println("广播消息失败: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 私聊消息
     * @param toUser
     * @param responseMessage
     */
    public void privateMessage(String[] toUser, ResponseMessage responseMessage){
        try {
            simpleChatHandler.privateMessage(toUser,objectMapper.writeValueAsString(responseMessage));
        } catch (JsonProcessingException e) {
            System.err.println("私法消息失败: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
